# -*- encoding: utf-8 -*-

import base64
from http.server import SimpleHTTPRequestHandler
import json
import socketserver
import sys
import os
import traceback
import signal
from urllib.parse import urlsplit, parse_qs


def signal_handler(sig, frame):
    os.kill(os.getpid(), signal.SIGTERM)


signal.signal(signal.SIGINT, signal_handler)


def updateStatus(pType, pData, pCode=None):
    if isinstance(pData, bytes):
        pData = pData.decode()
    obj = {'type': pType, 'data': pData, 'code': pCode}
    sys.stderr.write("\n%s\n" % json.dumps(obj).encode('utf-8'))


def redirect_handler_factory(url):

    if 'e2itcf' in url:
        job_type = 'cloudflare'
    else:
        job_type = 'captcha'
    to_write = '''
<!doctype html>
<html>
    <body style="background-color: #c8dee1">
        <img src=""/>
        <br><br><br><br>
        <center>
            <a href="%s" target="_blank"><button type="Button" style="color: white; font-weight: bold; font-size: x-large; text-align: center; padding: 4ex; border-radius: 20px; background-color:#448844">Get %s job</button></a>
        </center>
    </body>
</html>
''' % (url, job_type)

    with open(os.path.join(os.path.dirname(__file__), "htdocs/e2it.html"), 'w') as html:
        html.write(to_write)

    DIRECTORY = os.path.join(os.path.dirname(__file__), "htdocs")
    print(DIRECTORY)

    class RedirectHandler(SimpleHTTPRequestHandler):
        def __init__(self, *args, **kwargs):
            os.chdir(DIRECTORY)
            SimpleHTTPRequestHandler.__init__(self, *args, **kwargs)

        def do_GET(self):
            if self.path == '/':
                self.path = '/index.html'
            elif 'response' in self.path:
                self.send_response(200)
                self.send_header('content-type', 'text/html')
                self.end_headers()
                self.wfile.write(self.path.encode())
                parsed_path = urlsplit(self.path)
                query = parse_qs(parsed_path.query)
                token = query.get('token', None)[0]
                updateStatus('captcha_result', token)
                return
            SimpleHTTPRequestHandler.do_GET(self)
    return RedirectHandler


if __name__ == "__main__":
    try:
        if len(sys.argv) < 1:
            sys.stderr.write('Wrong parameters\n')
            sys.exit(1)

        CAPTCHA_DATA = json.loads(base64.b64decode(sys.argv[1]))
        IP = sys.argv[2]
        PORT = int(sys.argv[3])

        returnCode = 0

        siteUrl = CAPTCHA_DATA['siteUrl']
        siteKey = CAPTCHA_DATA['siteKey']
        captchaType = CAPTCHA_DATA['captchaType']

        socketserver.TCPServer.allow_reuse_address = True
        if captchaType == 'CF':
            httpd = socketserver.TCPServer((IP, PORT), redirect_handler_factory('%s#e2itcf_sep_c=%s' % (siteUrl, siteKey)))
        else:
            httpd = socketserver.TCPServer((IP, PORT), redirect_handler_factory('%s/#e2it?k=%s&st=%s' % (siteUrl, siteKey, captchaType)))
        print("Http Server Serving at port", PORT)
        httpd.serve_forever()
    except Exception:
        sys.stderr.write(traceback.format_exc())
        returnCode = -1

    sys.exit(returnCode)
